<?php
/**
 * Created by PhpStorm.
 * User: wumengmeng <wu_mengmeng@foxmail.com>
 * Date: 2019/4/26 0026
 * Time: 14:35
 */

namespace HiCommon\Service;

use HiCommon\Repository\CheckpointMakeDateRepository;
use HiCommon\Repository\OrderCheckpointRefundRepository;
use HiCommon\Repository\OrderCheckpointRepository;
use HiCommon\Repository\OrderCheckpointVehicleHelpdrivingRepository;
use HiCommon\Repository\OrderCheckpointVehicleRepository;
use HiCommon\Repository\OrderPayWechatRepository;
use HiCommon\Repository\ShopCheckpointServiceSpecsRepository;
use HiCommon\Repository\ShopRepository;
use HiCommon\Repository\UsersAppriseRepository;
use HiCommon\Repository\UsersRepository;
use HiCommon\Repository\UsersVehicleRepository;

class OrderCheckpointService extends BaseService
{

    /**
     * 检测年检预约单-主单输入数据
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_check_input_data_for_order(&$arr_input){

        $arr_input['order_sn']              = order_sn_njyy();//年检预约订单-生成订单号
        $arr_input['appointment_time_type'] = str_trim($arr_input['appointment_time_type']);
        $arr_input['appointment_num']       = intval($arr_input['appointment_num']);
        $arr_input['appointment_date']      = str_trim($arr_input['appointment_date']);
        $arr_input['appointment_times']     = str_trim($arr_input['appointment_times']);
        $arr_input['phone']                 = str_trim($arr_input['phone']);
        $arr_input['realname']              = str_trim($arr_input['realname']);
        $arr_input['shop_id']               = intval($arr_input['shop_id']);
        $arr_input['pay_state']             = 1;
//        $arr_input['refund_state']          = 0;
        $arr_input['appointment_state']     = 1;
//        $arr_input['check_state']           = 0;
//        $arr_input['appraise_state']        = 0;
        $arr_input['payment_method']        = '';
        if(!in_array($arr_input['appointment_time_type'],['am','pm'])){
            return hello_error('时段类型不能为空');
        }
        if(empty($arr_input['appointment_date'])){
            return hello_error('请选择预约日期');
        }
        if(empty($arr_input['appointment_times'])){
            return hello_error('请选择预约时间');
        }
        if(strlen($arr_input['phone']) <= 0){
            return hello_error('提交人手机号不能为空');
        }
        if(strlen($arr_input['realname']) <= 0){
            return hello_error('提交人姓名不能为空');
        }

        if($arr_input['shop_id'] <= 0){
            return hello_error('商家id不能为空');
        }
        if($arr_input['appointment_num'] <= 0){
            return hello_error('预约数量必须大于0');
        }
        return  hello_success('成功');
    }

    /**
     * 检测年检预约单-车辆子表输入数据
     *
     * @param array $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_check_input_data_for_order_vehicle(&$arr_input = []){
        $arr_input['order_sn'] = order_sn_njcl();//年检预约订单-车辆子单-生成订单号
        $arr_input['service_specs_ids'] = str_trim($arr_input['service_specs_ids']);
        $arr_input['users_vehicle_id'] = intval($arr_input['users_vehicle_id']);
        $arr_input['plate_no'] = str_trim($arr_input['plate_no']);
        $arr_input['vin'] = str_trim($arr_input['vin']);
        $arr_input['vehicle_type'] = str_trim($arr_input['vehicle_type']);
        $arr_input['owner'] = str_trim($arr_input['owner']);
        $arr_input['address'] = str_trim($arr_input['address']);
        $arr_input['use_character'] = str_trim($arr_input['use_character']);
        $arr_input['brand_model'] = str_trim($arr_input['brand_model']);
        $arr_input['engine_no'] = str_trim($arr_input['engine_no']);
        $arr_input['register_date'] = str_trim($arr_input['register_date']);
        $arr_input['issue_date'] = str_trim($arr_input['issue_date']);
        $arr_input['owner_phone'] = str_trim($arr_input['owner_phone']);
        $arr_input['is_pay_compulsory_insurance'] = intval($arr_input['is_pay_compulsory_insurance']);
        $arr_input['is_no_break_rule'] = intval($arr_input['is_no_break_rule']);
        if(mb_strlen($arr_input['service_specs_ids']) <= 0){
            return hello_error('请选择参数配置');
        }
        if(mb_strlen($arr_input['service_specs_ids']) > 50){
            return hello_error('参数配置不能超过50个字符');
        }
        if(mb_strlen($arr_input['plate_no']) <= 0){
            return hello_error('请填写车牌号码');
        }
        if(mb_strlen($arr_input['plate_no']) > 10){
            return hello_error('车牌号码不能超过10个字符');
        }
        if(mb_strlen($arr_input['vin']) <= 0){
            return hello_error('请填写车辆识别码');
        }
        if(mb_strlen($arr_input['vin']) > 20){
            return hello_error('车辆识别码不能超过20个字符');
        }
        if(mb_strlen($arr_input['vehicle_type']) <= 0){
            return hello_error('请填写车辆类型');
        }
        if(mb_strlen($arr_input['vehicle_type']) > 20){
            return hello_error('车辆类型不能超过20个字符');
        }
        if(mb_strlen($arr_input['owner']) <= 0){
            return hello_error('请填写所有人');
        }
        if(mb_strlen($arr_input['owner']) > 50){
            return hello_error('所有人不能超过50个字符');
        }
        if(mb_strlen($arr_input['address']) <= 0){
            return hello_error('请填写地址');
        }
        if(mb_strlen($arr_input['address']) > 100){
            return hello_error('地址不能超过100个字符');
        }
        if(mb_strlen($arr_input['use_character']) <= 0){
            return hello_error('请填写使用性质');
        }
        if(mb_strlen($arr_input['use_character']) > 50){
            return hello_error('使用性质不能超过50个字符');
        }
        if(mb_strlen($arr_input['brand_model']) <= 0){
            return hello_error('请填写品牌型号');
        }
        if(mb_strlen($arr_input['brand_model']) > 50){
            return hello_error('品牌型号不能超过50个字符');
        }
        if(mb_strlen($arr_input['engine_no']) <= 0){
            return hello_error('请填写发动机号码');
        }
        if(mb_strlen($arr_input['engine_no']) > 20){
            return hello_error('发动机号码不能超过20个字符');
        }
        if(mb_strlen($arr_input['register_date']) <= 0){
            return hello_error('请填写注册日期');
        }
        if(mb_strlen($arr_input['register_date']) > 10){
            return hello_error('注册日期不能超过10个字符');
        }
        if(mb_strlen($arr_input['issue_date']) <= 0){
            return hello_error('请填写发证日期');
        }
        if(mb_strlen($arr_input['issue_date']) > 10){
            return hello_error('发证日期不能超过10个字符');
        }
        if($arr_input['is_pay_compulsory_insurance'] != 1){
            return hello_error('请勾选已交强制险');
        }
        if($arr_input['is_no_break_rule'] != 1){
            return hello_error('请勾选无违章');
        }
        if($arr_input['price'] <= 0){
            return hello_error('产品价格错误');
        }
        return  hello_success('成功');
    }

    /**
     * 检测是否符合下单条件
     *
     * @param array $arr_input
     * @param array $arr_checkpoint_make_date
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_check_logic_before_submit($arr_input = [],&$arr_checkpoint_make_date = []){

        //提交订单前检测：1-检测用户是有预约中的年检预约单 2-只能在预约时间段2小时前才能下单
        $n_user_id = intval($arr_input['user_id']);
        $s_appointment_date = str_trim($arr_input['appointment_date']);//预约日期
        $s_appointment_times = str_trim($arr_input['appointment_times']);//预约时间段
        if($n_user_id <= 0){
            return hello_error('用户id不能为空');
        }
        if(mb_strlen($s_appointment_date) <= 0){
            return hello_error('预约日期不能为空');
        }
        if(mb_strlen($s_appointment_times) <= 0){
            return hello_error('预约时间不能为空');
        }

        //1 - 提前预约 - 只能在预约时间段2小时前才能下单
        $n_appointment_date_time = strtotime($s_appointment_date.' '.trim(explode('-',$s_appointment_times)[0]).':00');
        if(time() +   2 * 60 * 60 > $n_appointment_date_time){
            return hello_error('请提前2小时下单');
        }

        //2 - 同一时间只能提交一次订单，除非订单已支付或取消，才能提交下一单(检测用户是有预约中的年检预约单)
        $arr_option = ['where'=>['user_id'=>$n_user_id,'appointment_state'=>1]];
        $res = OrderCheckpointRepository::get_all($arr_option)->toarray();
        if(count($res) > 0){
            if($res[0]['pay_state'] == 1){
                return hello_warning('已有预约订单，请去前往支付',8);
            }
            return hello_error('已有预约订单，请耐心等待检测站处理');
        }

        //3 - 当前预约段内可预约数量不足时无法预约
        $res = OrderCheckpointService::api_check_logic_before_submit_for_appoint_num($arr_input,$arr_checkpoint_make_date);
        if($res['state'] != 0){
            return $res;
        }
        return  hello_success('成功');
    }

    /**
     * 当前预约段内可预约数量不足时无法预约
     *
     * @param array $arr_input
     * @param array $arr_checkpoint_make_date
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_check_logic_before_submit_for_appoint_num($arr_input = [],&$arr_checkpoint_make_date = []){
        $n_shop_id = $arr_input['shop_id'];
        $s_order_date = $arr_input['appointment_date'];
        $s_order_times = $arr_input['appointment_times'];
        $s_order_time_type = $arr_input['appointment_time_type'];
        $n_order_num = $arr_input['appointment_num'];

        /*查询时间段预定的总数量 已预订总数量 算出可预订的总量*/
        $arr_option = [
          'field'=>['id','am_time','am_num','am_order','pm_time','pm_num','pm_order'],
          'where'=>['checkpoint_id'=>$n_shop_id,'day'=>$s_order_date]
        ];
        $arr_make_date = CheckpointMakeDateRepository::get_all_data($arr_option)->toarray();

        $n_count_res = count($arr_make_date);
        if($n_count_res <= 0){
            return hello_error('当日不能预定');
        }
        elseif($n_count_res > 1){
            return hello_error('数据错误-重复，请联系客服');
        }
        else{
            $arr_order_data = $arr_make_date[0];
            if($s_order_times == $arr_order_data[$s_order_time_type.'_time']){
                $total_num = $arr_order_data[$s_order_time_type.'_num'];
                $has_order_num = $arr_order_data[$s_order_time_type.'_order'];
            }
            else{
                return hello_error('预约时段错误');
            }
            if($total_num < $has_order_num + $n_order_num){
                return hello_error('当前时间段预约已满');
            }
        }

        $arr_checkpoint_make_date = [
          'id'=>$arr_order_data['id'],
          'total_num'=>$total_num,
        ];
        return  hello_success('成功');

    }

    /**
     * 添加年检预约单-主单信息
     *
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_add_one_for_order(&$arr_input){
        $res = OrderCheckpointRepository::base_add_one($arr_input)->toarray();
        if(empty($res)){
            return hello_error('提交失败');
        }
        $arr_input = $res;
        return  hello_success('成功');

    }

    /**
     * 添加年检预约单车辆子表信息 - 一辆车
     *
     * @param     $arr_input
     * @param int $n_order_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_add_one_for_order_vehicle(&$arr_input,$n_order_id = 0){
        $arr_input['order_checkpoint_id'] = $n_order_id;
        $res = OrderCheckpointVehicleRepository::add_one($arr_input)->toarray();
        if(empty($res)){
            return hello_error('提交失败');
        }

        $arr_input = $res;
        return  hello_success('成功');

    }


    /**
     * 添加年检预约单车辆子表信息 - 多辆车
     *
     * @param     $arr_input
     * @param int $n_order_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_add_many_for_order_vehicle($arr_input){
        $res = OrderCheckpointVehicleRepository::base_add_many($arr_input);
        if(!$res){
            return hello_error('提交失败');
        }

        return  hello_success('成功');

    }


    /**
     * 更新用户车辆档案和信息
     *
     * @param $n_uid
     * @param $n_user_vehicle_id
     * @param $arr_user
     * @param $arr_input_user
     * @param $arr_input_vehicle
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_refresh_user_and_user_vehicle($n_uid,$arr_user,$arr_input_user,$arr_input_vehicle){

        $n_user_vehicle_id = intval($arr_input_vehicle['users_vehicle_id']);

        //添加或者更新用户车辆档案
        unset($arr_input_vehicle['is_pay_compulsory_insurance']);
        unset($arr_input_vehicle['is_no_break_rule']);
        unset($arr_input_vehicle['order_sn']);
        unset($arr_input_vehicle['price']);
        unset($arr_input_vehicle['is_call_helpdriving']);
        unset($arr_input_vehicle['service_specs_ids']);
        unset($arr_input_vehicle['users_vehicle_id']);

        if($n_user_vehicle_id == 0){
            $res = UsersVehicleRepository::base_add_one($arr_input_vehicle)->toarray();
            if(empty($res)){
                return hello_error('操作失败');
            }
        }
//        else{
//            $arr_input_vehicle['id'] = $n_user_vehicle_id;
//            $res = UsersVehicleRepository::base_edit_one($arr_input_vehicle);
//            if($res === false){
//                return hello_error('操作失败');
//            }
//        }
        
        //如果用户已经编辑了手机号和姓名，则不更新，否则部分更新或者全部更新
        if(empty($arr_user['phone']) || empty($arr_user['realname'])){
            //更新用户信息
            $arr_data_user['id'] = $n_uid;
            if(empty($arr_user['phone'])){
                $arr_data_user['phone'] = $arr_input_user['phone'];
            }
            if(empty($arr_user['realname'])){
                $arr_data_user['realname'] = $arr_input_user['realname'];
            }
            $res = UsersRepository::base_edit_one($arr_data_user);
            if(!$res){
                return hello_error('提交失败1');
            }
        }
        return  hello_success('成功');

    }

    /**
     * 个人单-到站检车-检测输入数据是否完整并符合规范
     *
     * @param $arr_input_order
     * @param $arr_input_order_vehicle
     * @param $arr_shop_products
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_check_data_for_personal_autonomy(&$arr_input_order,&$arr_input_order_vehicle){

        //检测年检预约单主单输入数据
        $res = OrderCheckpointService::api_check_input_data_for_order($arr_input_order);
        if($res['state'] != 0){
            return $res;
        }

        //检测年检预约单车辆子表输入数据
        $res = OrderCheckpointService::api_check_input_data_for_order_vehicle($arr_input_order_vehicle);
        if($res['state'] != 0){
            return $res;
        }

        return  hello_success('成功');

    }

    /**
 * 个人单-到站检车-提交订单相关数据数据
 *
 * @param array $arr_ids
 * @param array $arr_data
 *
 * @return array
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
    public function api_save_data_for_personal_autonomy($n_uid = 0,$arr_data = []){

        $arr_user = $arr_data['arr_user'];
        $arr_input_user = $arr_data['arr_input_user'];
        $arr_input_order = $arr_data['arr_input_order'];
        $arr_input_order_vehicle = $arr_data['arr_input_order_vehicle'];
        $arr_checkpoint_make_date = $arr_data['arr_checkpoint_make_date'];

        //更新用户车辆档案和信息
        $res = OrderCheckpointService::api_refresh_user_and_user_vehicle($n_uid,$arr_user,$arr_input_user,$arr_input_order_vehicle);
        if($res['state'] != 0){
            return $res;
        }

        //添加年检预约单主单信息
        $arr_input_order['price'] = $arr_input_order_vehicle['price'];
        $res = OrderCheckpointService::api_add_one_for_order($arr_input_order);
        if($res['state'] != 0){
            return $res;
        }

        //添加年检预约单车辆子表信息 - 一辆车
        $n_order_id = $arr_input_order['id'];
        $res = OrderCheckpointService::api_add_one_for_order_vehicle($arr_input_order_vehicle,$n_order_id);
        if($res['state'] != 0){
            return $res;
        }


        //扣除库存

        //增加已预订数量（即扣库存）
        //累加已预约的数量-有上限值
        $n_id = $arr_checkpoint_make_date['id'];
        $n_total_num = $arr_checkpoint_make_date['total_num'];
        $n_order_num = $arr_input_order['appointment_num'];
        $n_order_time_type = $arr_input_order['appointment_time_type'];
        $res = CheckpointMakeDateService::api_increase_order_num($n_id,$n_order_time_type,$n_order_num,$n_total_num);
        if($res['state'] != 0){
            return $res;
        }

        $arr_data = ['id'=>$n_order_id];
        return  hello_success('成功',$arr_data);
    }

    /**
     * 企业单-到站检车-提交订单相关数据数据
     *
     * @param array $arr_ids
     * @param array $arr_data
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_save_data_for_company_autonomy($n_uid,$arr_data = []){

//        $n_uid = $arr_ids['user_id'];
//        $n_user_vehicle_id = $arr_ids['user_vehicle_id'];
        $arr_user = $arr_data['arr_user'];
        $arr_input_user = $arr_data['arr_input_user'];
        $arr_input_order = $arr_data['arr_input_order'];
        $arr_input_order_vehicle = $arr_data['arr_input_order_vehicle'];
        $arr_checkpoint_make_date = $arr_data['arr_checkpoint_make_date'];

        //更新用户信息
        //如果用户已经编辑了手机号和姓名，则不更新，否则部分更新或者全部更新
        if(empty($arr_user['phone']) || empty($arr_user['realname'])){
            //更新用户信息
            $arr_data_user['id'] = $n_uid;
            if(empty($arr_user['phone'])){
                $arr_data_user['phone'] = $arr_input_user['phone'];
            }
            if(empty($arr_user['realname'])){
                $arr_data_user['realname'] = $arr_input_user['realname'];
            }
            $res = UsersRepository::base_edit_one($arr_data_user);
            if(!$res){
                return hello_error('提交失败1');
            }
        }

        //添加年检预约单主单信息
        $res = OrderCheckpointService::api_add_one_for_order($arr_input_order);
        if($res['state'] != 0){
            return $res;
        }

        //添加年检预约单车辆子表信息 - 一辆车
        $n_order_id = $arr_input_order['id'];
        foreach ($arr_input_order_vehicle as &$value)
        {
            $value['order_checkpoint_id'] = $n_order_id;
        }
        $res = OrderCheckpointService::api_add_many_for_order_vehicle($arr_input_order_vehicle);
        if($res['state'] != 0){
            return $res;
        }


        //扣除库存

        //增加已预订数量（即扣库存）
        //累加已预约的数量-有上限值
        $n_id = $arr_checkpoint_make_date['id'];
        $n_total_num = $arr_checkpoint_make_date['total_num'];
        $n_order_num = $arr_input_order['appointment_num'];
        $n_order_time_type = $arr_input_order['appointment_time_type'];
        $res = CheckpointMakeDateService::api_increase_order_num($n_id,$n_order_time_type,$n_order_num,$n_total_num);

        if($res['state'] != 0){
            return $res;
        }

        $arr_data = ['id'=>$n_order_id];
        return  hello_success('成功',$arr_data);
    }

    /**
     * 个人单-到站检车-数据准备
     *
     * @param $n_uid
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_prepare_data_for_personal_autonomy($n_uid,$arr_input){
        //数据准备
        $arr_input_order_vehicle = $arr_input['arr_vehicle'];//车辆子表数据
        unset($arr_input['arr_vehicle']);

        $arr_input_order = $arr_input;//主单数据
        $n_user_vehicle_id = intval($arr_input_order['user_vehicle_id']);//用户车辆id
        unset($arr_input_order['user_vehicle_id']);

        $arr_input_order['user_id'] = $n_uid;
        $arr_input_order['main_type'] = 1;//默认个人单
        $arr_input_order['appointment_num'] = 1;//默认数量1

        //检测机构所有规格参数配置集合
        $arr_option = [
          'where'=>['shop_id'=>intval($arr_input_order['shop_id']),'status'=>1],
          'field'=>['id','pid','name','price'],
        ];
        $arr_shop_products = ShopCheckpointServiceSpecsRepository::base_get_all($arr_option)->toarray();


        //补全车辆子单数据
        //计算检车价格
        $arr_service_specs_ids= explode(':',$arr_input_order_vehicle['service_specs_ids']);
        $oc_data = collect($arr_shop_products)->whereIn('id',$arr_service_specs_ids);
        $arr_input_order_vehicle['price'] = $oc_data->sum('price');
        $arr_input_order_vehicle['is_call_helpdriving'] = 2;
        $arr_input_order_vehicle['users_vehicle_id'] = $n_user_vehicle_id;
        $arr_input_order['price'] = $arr_input_order_vehicle['price'];
        $arr_input_order['service_specs_json'] = json_encode($arr_shop_products);

        return [$arr_input_order,$arr_input_order_vehicle];
    }

    /**
     * 年检预约单-个人单-到站检车 - 提交订单
     *
     * @param $n_uid
     * @param $arr_input
     * @param $arr_user
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_submit_personal_autonomy($n_uid,$arr_input,$arr_user = []){

        //个人单-到站检车-数据准备
        list($arr_input_order,$arr_input_order_vehicle) = OrderCheckpointService::api_prepare_data_for_personal_autonomy($n_uid,$arr_input);

        //个人单-到站检车-检测输入数据是否完整并符合规范
        $res = OrderCheckpointService::api_check_data_for_personal_autonomy($arr_input_order,$arr_input_order_vehicle);
        if($res['state'] != 0){
            return $res;
        }

        //个人单-到站检车-检测是否符合下单条件
        $res = OrderCheckpointService::api_check_logic_before_submit($arr_input_order,$arr_checkpoint_make_date);
        if($res['state'] != 0){
            return $res;
        }

        //个人单-到站检车-提交订单相关数据数据
        $arr_input_user = [
          'phone'=>$arr_input_order['phone'],
          'realname'=>$arr_input_order['realname'],
        ];

        $arr_data = [
          'arr_user'=>$arr_user,
          'arr_input_user'=>$arr_input_user,
          'arr_input_order'=>$arr_input_order,
          'arr_input_order_vehicle'=>$arr_input_order_vehicle,
          'arr_checkpoint_make_date'=>$arr_checkpoint_make_date,
        ];

        $res = OrderCheckpointService::api_save_data_for_personal_autonomy($n_uid,$arr_data);
        return $res;
    }

    /**
     * 检查年检预约单-代驾子订单数据
     *
     * @param $data
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_check_data_for_checkpoint_order_vehicle_helpdriving(&$data){
        $data['order_sn']        = str_trim($data['order_sn']);
        $data['start_longitude'] = str_trim($data['start_longitude']);
        $data['start_latitude']  = str_trim($data['start_latitude']);
        $data['start_address']   = str_trim($data['start_address']);

        $data['center_longitude']   = str_trim($data['center_longitude']);
        $data['center_latitude']    = str_trim($data['center_latitude']);
        $data['center_address']     = str_trim($data['center_address']);

        $data['end_longitude']   = str_trim($data['end_longitude']);
        $data['end_latitude']    = str_trim($data['end_latitude']);
        $data['end_address']     = str_trim($data['end_address']);

        $data['take_car_time']     = str_trim($data['take_car_time']);
        if (strlen($data['start_longitude']) <= 0) {
            return hello_error('取车点经度不能为空');
        }
        if (strlen($data['start_latitude']) <= 0) {
            return hello_error('取车点纬度不能为空');
        }
        if (strlen($data['start_address']) <= 0) {
            return hello_error('取车点地址不能为空');
        }

        if (strlen($data['center_longitude']) <= 0) {
            return hello_error('检测站经度不能为空');
        }
        if (strlen($data['center_latitude']) <= 0) {
            return hello_error('检测站纬度不能为空');
        }
        if (strlen($data['center_address']) <= 0) {
            return hello_error('检测站地址不能为空');
        }

        if (strlen($data['end_longitude']) <= 0) {
            return hello_error('还车点经度不能为空');
        }
        if (strlen($data['end_latitude']) <= 0) {
            return hello_error('还车点纬度不能为空');
        }
        if (strlen($data['end_address']) <= 0) {
            return hello_error('还车点地址不能为空');
        }
        if (strlen($data['take_car_time']) <= 0) {
            return hello_error('取车时间不能为空');
        }

        return hello_success('成功');
    }

    /**
     * 个人单-代驾检车-数据准备
     *
     * @param $n_uid
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_prepare_data_for_personal_helpdriving($n_uid,$arr_input){

        //数据准备
        $arr_input_order_vehicle = $arr_input['arr_vehicle'];//车辆子表数据
        unset($arr_input['arr_vehicle']);

        $arr_input_order_vehicle_helpdriving = $arr_input['arr_vehicle_helpdriving'];//车辆代驾子表数据
        unset($arr_input['arr_vehicle_helpdriving']);

        $arr_input_order = $arr_input;//主单数据
        $n_user_vehicle_id = intval($arr_input_order['user_vehicle_id']);//用户车辆id
        unset($arr_input_order['user_vehicle_id']);


        $arr_input_order['user_id'] = $n_uid;
        $arr_input_order['main_type'] = 1;//默认个人单
        $arr_input_order['appointment_num'] = 1;//默认数量1

        //检测机构所有规格参数配置集合
        $arr_option = [
          'where'=>['shop_id'=>intval($arr_input_order['shop_id']),'status'=>1],
          'field'=>['id','name','price'],
        ];
        $arr_shop_products = ShopCheckpointServiceSpecsRepository::base_get_all($arr_option)->toarray();


        //补全车辆子单数据
        //计算检车价格
        $arr_service_specs_ids= explode(':',$arr_input_order_vehicle['service_specs_ids']);
        $oc_data = collect($arr_shop_products)->whereIn('id',$arr_service_specs_ids);
        $arr_input_order_vehicle['price'] = $oc_data->sum('price');
        $arr_input_order_vehicle['is_call_helpdriving'] = 1;
        $arr_input_order_vehicle['users_vehicle_id'] = $n_user_vehicle_id;

        $arr_input_order['price'] = $arr_input_order_vehicle['price'];
        $arr_input_order['service_specs_json'] = json_encode($arr_shop_products);

        return [$arr_input_order,$arr_input_order_vehicle,$arr_input_order_vehicle_helpdriving];

    }

    /**
     * 个人单-代驾检车-检测输入数据是否完整并符合规范
     *
     * @param $arr_input_order
     * @param $arr_input_order_vehicle
     * @param $arr_input_order_vehicle_helpdriving
     * @param $arr_shop_products
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_check_data_for_personal_helpdriving(&$arr_input_order,&$arr_input_order_vehicle,&$arr_input_order_vehicle_helpdriving){

        //检测年检预约单-主单输入数据
        $res = OrderCheckpointService::api_check_input_data_for_order($arr_input_order);
        if($res['state'] != 0){
            return $res;
        }

        //检测年检预约单-车辆子表输入数据
        $res = OrderCheckpointService::api_check_input_data_for_order_vehicle($arr_input_order_vehicle);
        if($res['state'] != 0){
            return $res;
        }

        //检查年检预约单-代驾子订单数据
        $arr_input_order_vehicle_helpdriving['order_sn'] = $arr_input_order_vehicle['order_sn'];//订单总价格
        $res = OrderCheckpointService::api_check_data_for_checkpoint_order_vehicle_helpdriving($arr_input_order_vehicle_helpdriving);
        if($res['state'] != 0){
            return $res;
        }

        return  hello_success('成功');

    }

    /**
     * 个人单-代驾检车-提交订单相关数据数据
     *
     * @param array $arr_ids
     * @param array $arr_data
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_save_data_for_personal_helpdriving($n_uid = 0,$arr_data = []){

        $arr_user = $arr_data['arr_user'];
        $arr_input_user = $arr_data['arr_input_user'];
        $arr_input_order = $arr_data['arr_input_order'];
        $arr_input_order_vehicle = $arr_data['arr_input_order_vehicle'];
        $arr_input_order_vehicle_helpdriving = $arr_data['arr_input_order_vehicle_helpdriving'];
        $arr_checkpoint_make_date = $arr_data['arr_checkpoint_make_date'];

        //更新用户车辆档案和信息
        $res = OrderCheckpointService::api_refresh_user_and_user_vehicle($n_uid,$arr_user,$arr_input_user,$arr_input_order_vehicle);
        if($res['state'] != 0){
            return $res;
        }

        //添加年检预约单-主单信息
        $arr_input_order['price'] = $arr_input_order_vehicle['price'];
        $res = OrderCheckpointService::api_add_one_for_order($arr_input_order);
        if($res['state'] != 0){
            return $res;
        }

        //添加年检预约单车辆子表信息 - 一辆车
        $n_order_id = $arr_input_order['id'];
        $res = OrderCheckpointService::api_add_one_for_order_vehicle($arr_input_order_vehicle,$n_order_id);
        if($res['state'] != 0){
            return $res;
        }

        //添加车辆代驾子表数据
        $res = OrderCheckpointVehicleHelpdrivingRepository::add_one($arr_input_order_vehicle_helpdriving)->toarray();
        if(empty($res)){
            return hello_error('提交失败');
        }


        //扣除库存

        //增加已预订数量（即扣库存）
        //累加已预约的数量-有上限值
        $n_id = $arr_checkpoint_make_date['id'];
        $n_total_num = $arr_checkpoint_make_date['total_num'];
        $n_order_num = $arr_input_order['appointment_num'];
        $n_order_time_type = $arr_input_order['appointment_time_type'];
        $res = CheckpointMakeDateService::api_increase_order_num($n_id,$n_order_time_type,$n_order_num,$n_total_num);
        if($res['state'] != 0){
            return $res;
        }

        $arr_data = ['id'=>$n_order_id];
        return  hello_success('成功',$arr_data);
    }

    /**
     * 年检预约单 - 个人单 - 代驾检车 - 提交订单
     *
     * @param $n_uid
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_submit_personal_helpdriving($n_uid,$arr_input,$arr_user = []){

        //个人单-代驾检车-数据准备
        list($arr_input_order,$arr_input_order_vehicle,$arr_input_order_vehicle_helpdriving) = OrderCheckpointService::api_prepare_data_for_personal_helpdriving($n_uid,$arr_input);

        //个人单-代驾检车-检测输入数据是否完整并符合规范
        $res = OrderCheckpointService::api_check_data_for_personal_helpdriving($arr_input_order,$arr_input_order_vehicle,$arr_input_order_vehicle_helpdriving);
        if($res['state'] != 0){
            return $res;
        }

        //检测是否符合下单条件
        $res = OrderCheckpointService::api_check_logic_before_submit($arr_input_order,$arr_checkpoint_make_date);
        if($res['state'] != 0){
            return $res;
        }

        //个人单-代驾检车-提交订单相关数据数据
        $arr_input_user = [
          'phone'=>$arr_input_order['phone'],
          'realname'=>$arr_input_order['realname'],
        ];
        $arr_data = [
          'arr_user'=>$arr_user,
          'arr_input_user'=>$arr_input_user,
          'arr_input_order'=>$arr_input_order,
          'arr_input_order_vehicle'=>$arr_input_order_vehicle,
          'arr_input_order_vehicle_helpdriving'=>$arr_input_order_vehicle_helpdriving,
          'arr_checkpoint_make_date'=>$arr_checkpoint_make_date,
        ];
        $res = OrderCheckpointService::api_save_data_for_personal_helpdriving($n_uid,$arr_data);
        return $res;
    }


    /**
     * 企业单-到站检车-数据准备
     *
     * @param $n_uid
     * @param $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_prepare_data_for_company_autonomy($n_uid,$arr_input){
        //数据准备
        $arr_input_order_vehicle = $arr_input['arr_vehicle'];//车辆子表数据
        unset($arr_input['arr_vehicle']);

        $arr_input_order = $arr_input;//主单数据
//        $arr_input_user = intval($arr_input_order['arr_user']);//车辆子表输入用户数据
//        unset($arr_input_order['arr_user']);

//        $n_user_vehicle_id = intval($arr_input_order['user_vehicle_id']);//用户车辆id
//        unset($arr_input_order['user_vehicle_id']);

        $arr_input_order['user_id'] = $n_uid;
        $arr_input_order['main_type'] = 2;//企业单
        $arr_input_order['appointment_num'] = count($arr_input_order_vehicle);//数量

        //检测机构所有规格参数配置集合
        $arr_option = [
          'where'=>['shop_id'=>intval($arr_input_order['shop_id']),'status'=>1],
          'field'=>['id','name','price'],
        ];
        $arr_shop_products = ShopCheckpointServiceSpecsRepository::base_get_all($arr_option)->toarray();

        //补全车辆子单数据
        $arr_ids = arr_value_to_ids($arr_input_order_vehicle,'users_vehicle_id');
        $arr_option = [
          'field'=>['id','plate_no','vin','vehicle_type','owner','owner_phone','address','use_character','brand_model','engine_no','register_date','issue_date'],
          'where'=>['status'=>1]
        ];
        $arr_user_vehicle = UsersVehicleRepository::base_get_all_by_wherein('id',$arr_ids,$arr_option)->toarray();
        $oc_user_vehicle = collect($arr_user_vehicle);
        foreach ($arr_input_order_vehicle as &$value)
        {

            //计算检车价格
            $arr_service_specs_ids= explode(':',$value['service_specs_ids']);
            $oc_data = collect($arr_shop_products)->whereIn('id',$arr_service_specs_ids);
            $value['price'] = $oc_data->sum('price');
            $arr_temp_value = $oc_user_vehicle->where('id',$value['users_vehicle_id'])->first();
            unset($arr_temp_value['id']);
            $value['is_call_helpdriving'] = 2;

            $value = array_merge($value,$arr_temp_value);
        }
        $arr_input_order['service_specs_json'] = json_encode($arr_shop_products);
        $arr_input_order['price'] = collect($arr_input_order_vehicle)->sum('price');
        return [$arr_input_order,$arr_input_order_vehicle];
    }


    /**
     * 检测年检预约单-企业单-车辆子表输入数据
     *
     * @param array $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_check_input_data_for_order_vehicle_simple(&$arr_input = []){
        $arr_input['order_sn'] = order_sn_njcl();//年检预约订单-车辆子单-生成订单号
        $arr_input['service_specs_ids'] = str_trim($arr_input['service_specs_ids']);
        $arr_input['plate_no'] = str_trim($arr_input['plate_no']);
        $arr_input['vin'] = str_trim($arr_input['vin']);
        $arr_input['vehicle_type'] = str_trim($arr_input['vehicle_type']);
        $arr_input['owner'] = str_trim($arr_input['owner']);
        $arr_input['address'] = str_trim($arr_input['address']);
        $arr_input['use_character'] = str_trim($arr_input['use_character']);
        $arr_input['brand_model'] = str_trim($arr_input['brand_model']);
        $arr_input['engine_no'] = str_trim($arr_input['engine_no']);
        $arr_input['register_date'] = str_trim($arr_input['register_date']);
        $arr_input['issue_date'] = str_trim($arr_input['issue_date']);
        $arr_input['owner_phone'] = str_trim($arr_input['owner_phone']);
        $arr_input['is_pay_compulsory_insurance'] = intval($arr_input['is_pay_compulsory_insurance']);
        $arr_input['is_no_break_rule'] = intval($arr_input['is_no_break_rule']);
        if(mb_strlen($arr_input['service_specs_ids']) <= 0){
            return hello_error('请选择参数配置');
        }
        if(mb_strlen($arr_input['service_specs_ids']) > 50){
            return hello_error('参数配置不能超过50个字符');
        }
        if(mb_strlen($arr_input['plate_no']) <= 0){
            return hello_error('请填写车牌号码');
        }
        if(mb_strlen($arr_input['plate_no']) > 10){
            return hello_error('车牌号码不能超过10个字符');
        }
        if(mb_strlen($arr_input['vin']) <= 0){
            return hello_error('请填写车辆识别码');
        }
        if(mb_strlen($arr_input['vin']) > 20){
            return hello_error('车辆识别码不能超过20个字符');
        }
        if(mb_strlen($arr_input['vehicle_type']) <= 0){
            return hello_error('请填写车辆类型');
        }
        if(mb_strlen($arr_input['vehicle_type']) > 20){
            return hello_error('车辆类型不能超过20个字符');
        }
        if(mb_strlen($arr_input['owner']) <= 0){
            return hello_error('请填写所有人');
        }
        if(mb_strlen($arr_input['owner']) > 50){
            return hello_error('所有人不能超过50个字符');
        }
        if(mb_strlen($arr_input['address']) <= 0){
            return hello_error('请填写地址');
        }
        if(mb_strlen($arr_input['address']) > 100){
            return hello_error('地址不能超过100个字符');
        }
        if(mb_strlen($arr_input['use_character']) <= 0){
            return hello_error('请填写使用性质');
        }
        if(mb_strlen($arr_input['use_character']) > 50){
            return hello_error('使用性质不能超过50个字符');
        }
        if(mb_strlen($arr_input['brand_model']) <= 0){
            return hello_error('请填写品牌型号');
        }
        if(mb_strlen($arr_input['brand_model']) > 50){
            return hello_error('品牌型号不能超过50个字符');
        }
        if(mb_strlen($arr_input['engine_no']) <= 0){
            return hello_error('请填写发动机号码');
        }
        if(mb_strlen($arr_input['engine_no']) > 20){
            return hello_error('发动机号码不能超过20个字符');
        }
        if(mb_strlen($arr_input['register_date']) <= 0){
            return hello_error('请填写注册日期');
        }
        if(mb_strlen($arr_input['register_date']) > 10){
            return hello_error('注册日期不能超过10个字符');
        }
        if(mb_strlen($arr_input['issue_date']) <= 0){
            return hello_error('请填写发证日期');
        }
        if(mb_strlen($arr_input['issue_date']) > 10){
            return hello_error('发证日期不能超过10个字符');
        }
        if($arr_input['is_pay_compulsory_insurance'] != 1){
            return hello_error('请勾选已交强制险');
        }
        if($arr_input['is_no_break_rule'] != 1){
            return hello_error('请勾选无违章');
        }

        return  hello_success('成功');
    }

    /**
     * 企业单-到站检车-检测输入数据是否完整并符合规范
     *
     * @param $arr_input_order
     * @param $arr_input_order_vehicle
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_check_data_for_company_autonomy(&$arr_input_order,&$arr_input_order_vehicle){

        //检测年检预约单主单输入数据
        $res = OrderCheckpointService::api_check_input_data_for_order($arr_input_order);
        if($res['state'] != 0){
            return $res;
        }

        foreach ($arr_input_order_vehicle as &$value)
        {
            //检测年检预约单车辆子表输入数据
            $res = OrderCheckpointService::api_check_input_data_for_order_vehicle_simple($value);
            if($res['state'] != 0){
                return $res;
            }
        }
        return  hello_success('成功');

    }

    /**
     * 年检预约单-企业单-到站检车 - 提交订单
     *
     * @param $n_uid
     * @param $arr_input
     * @param $arr_user
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_submit_company_autonomy($n_uid,$arr_input,$arr_user){

        //企业单-到站检车-数据准备
        list($arr_input_order,$arr_input_order_vehicle) = OrderCheckpointService::api_prepare_data_for_company_autonomy($n_uid,$arr_input);

        //企业单-到站检车-检测输入数据是否完整并符合规范
        $arr_input_order['user_company_id'] = intval($arr_input_order['user_company_id']);
        if($arr_input_order['user_company_id'] <= 0){
            return hello_error('用户企业ID不能为空');
        }
        $res = OrderCheckpointService::api_check_data_for_company_autonomy($arr_input_order,$arr_input_order_vehicle);
        if($res['state'] != 0){
            return $res;
        }

        //企业单-到站检车-检测是否符合下单条件
        $res = OrderCheckpointService::api_check_logic_before_submit($arr_input_order,$arr_checkpoint_make_date);
        if($res['state'] != 0){
            return $res;
        }

        //企业单-到站检车-提交订单相关数据数据
        $arr_input_user = [
          'phone'=>$arr_input_order['phone'],
          'realname'=>$arr_input_order['realname'],
        ];
//        $arr_ids = [
//          'user_id'=>$n_uid,
//          'user_vehicle_id'=>$n_user_vehicle_id,
//        ];
        $arr_data = [
          'arr_user'=>$arr_user,
          'arr_input_user'=>$arr_input_user,
          'arr_input_order'=>$arr_input_order,
          'arr_input_order_vehicle'=>$arr_input_order_vehicle,
          'arr_checkpoint_make_date'=>$arr_checkpoint_make_date,
        ];
        $res = OrderCheckpointService::api_save_data_for_company_autonomy($n_uid,$arr_data);
        return $res;
    }


    /*到站检车转为代驾*/
    public function api_personal_change_to_helpdriving($arr_input){
        filter_input_data($arr_input);
        if(mb_strlen($arr_input['order_sn']) <= 0){
            return hello_error('请输入车辆子单编号');
        }
        if(mb_strlen($arr_input['start_longitude']) <= 0){
            return hello_error('请输入取车点经度');
        }
        if(mb_strlen($arr_input['start_latitude']) <= 0){
            return hello_error('请输入取车点纬度');
        }
        if(mb_strlen($arr_input['start_address']) <= 0){
            return hello_error('请输入取车点地址');
        }
        if(mb_strlen($arr_input['end_longitude']) <= 0){
            return hello_error('请输入还车点经度');
        }
        if(mb_strlen($arr_input['end_latitude']) <= 0){
            return hello_error('请输入还车点纬度');
        }
        if(mb_strlen($arr_input['end_address']) <= 0){
            return hello_error('请输入还车点地址');
        }
        if(mb_strlen($arr_input['center_longitude']) <= 0){
            return hello_error('请输入检测站经度');
        }
        if(mb_strlen($arr_input['center_latitude']) <= 0){
            return hello_error('请输入检测站纬度');
        }
        if(mb_strlen($arr_input['center_address']) <= 0){
            return hello_error('请输入检测站地址');
        }
        if(mb_strlen($arr_input['take_car_time']) <= 0){
            return hello_error('请输入取车时间');
        }

        //订单类型改为代驾
        $arr_where = ['order_sn'=>$arr_input['order_sn']];
        $arr_data = ['is_call_helpdriving'=>1];
        $result = OrderCheckpointVehicleRepository::base_edit_by_where($arr_where,$arr_data);
        if(!$result){
            return hello_error('操作失败',$result,'订单类型改为代驾失败');
        }

        //添加代驾订单信息
        $result = OrderCheckpointVehicleHelpdrivingRepository::base_add_one($arr_input)->toarray();
        if(empty($result)){
            return hello_error('操作失败',[],'添加代驾订单信息失败');
        }
        return  hello_success('操作成功');

    }

    /**
     * 30分钟内未支付订单自动取消预约 同时返还库存
     *
     * @param array $arr_order
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_auto_cancle_appointment($arr_order = []){
        $n_id = $arr_order['id'];

        //取消预约
        $arr_data = [
          'id'=>$n_id,
          'appointment_state'=>3,
        ];
        $res = OrderCheckpointRepository::edit_one($arr_data);
        if($res == 0){
            return hello_error('取消失败',[],'状态修改失败');
        }

        //释放预约数量
        $arr_where = [
          'checkpoint_id'=>$arr_order['shop_id'],
          'day'=>$arr_order['appointment_date'],
          $arr_order['appointment_time_type'].'_time'=>$arr_order['appointment_times'],
        ];
        $s_field =  $arr_order['appointment_time_type'].'_order';
        $n_order_num = $arr_order['appointment_num'];
        $res = CheckpointMakeDateRepository::decrease_num_limit_by_where($arr_where,$s_field,$n_order_num);
        if($res == 0){
            return hello_error('取消失败',[],'释放预约数量失败');
        }
        return hello_success('取消成功');
    }

    /**
     * 7天未评价预约订单自动5星评价
     *
     * @param        $n_order_id
     * @param        $n_shop_id
     * @param        $n_uid
     * @param int    $n_score
     * @param string $s_content
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_auto_apprise_appointment_order($n_order_id,$n_shop_id,$n_uid,$n_score = 5,$s_content = ''){
        //修改订单评价状态
        $res = OrderCheckpointRepository::change_one_state($n_order_id,2,'appraise_state');
        if(!$res){
            return hello_error('评价失败1');
        }

        //添加订单评价
        $arr_data = [
          'type'=>11,
          'order_id'=>$n_order_id,
          'shop_id'=>$n_shop_id,
          'score'=>$n_score,
          'user_id'=>$n_uid,
          'content'=>$s_content,
        ];
        $res = UsersAppriseRepository::base_add_one($arr_data)->toarray();
        if(empty($res)){
            return hello_error('评价失败');
        }


        //查询评价总分 + 评价数量
        $arr_where = ['shop_id'=>$n_shop_id];
        $n_total_score = UsersAppriseRepository::base_get_sum_by_where($arr_where,'score');
        $n_total_num = UsersAppriseRepository::base_get_count_by_where($arr_where);
        $n_score = number_format_money($n_total_score/$n_total_num);

        //更新商家评分
        $arr_data = ['id'=>$n_shop_id,'check_score'=>$n_score];
        $res = ShopRepository::edit_one($arr_data);
        if(!$res){
            return hello_error('评价失败2');
        }
        return  hello_success('评价成功');
    }


    /**
     * 取消订单【未支付订单】
     *
     * @param $n_uid
     * @param $n_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_cancle_appointment_notpay($n_uid, $n_id){

        $arr_field = ['id', 'shop_id', 'user_id','appointment_date', 'appointment_times', 'appointment_time_type', 'appointment_num', 'pay_state','appointment_state', 'created_at'];
        $result = OrderCheckpointRepository::base_find_one($n_id,['field'=>$arr_field]);
        if(is_null($result)){
            return hello_error('订单不存在');
        }
        $result = $result->toarray();

        //只有未支付的订单才可以取消
        if($result['pay_state'] != 1 && $result['appointment_state'] != 1 ){
            return hello_error('订单无法取消');
        }
        if($result['pay_state'] == 2){
            return hello_error('订单已支付，不能取消订单');
        }
        if($result['appointment_state'] == 3){
            return hello_error('订单已取消');
        }
        if($result['user_id'] != $n_uid){
            return hello_error('只能操作自己的订单');
        }

        //取消订单
        $res = OrderCheckpointService::api_auto_cancle_appointment($result);
        return $res;
    }

    /*到站检车 - 企业单*/
    public function autonomy_check_for_company($n_uid,$arr_input){
        try {

            return  hello_success('成功');
        }
        catch (\Exception $exception) {
            return hello_error('失败',[],$exception->getMessage());

        }
    }

    /*代驾检车 - 企业单*/
    public function helpdriving_check_for_company($n_uid,$arr_input){
        try {

            return  hello_success('成功');
        }
        catch (\Exception $exception) {
            return hello_error('失败',[],$exception->getMessage());

        }
    }

//    /**
//     * 已完成预约订单-商家
//     *
//     * @param int   $n_shop_id
//     *
//     * @return array
//     * @author wumengmeng <wu_mengmeng@foxmail.com>
//     */
//    public function api_complete_order_list_for_shop($n_shop_id = 0,$arr_search = []){
//        $arr_where['shop_id'] = $n_shop_id;
////        $arr_where['check_state'] = 2;
//        $arr_option['with'] = ['check_vehicle','shop','user','user_company'];
//
//        $res = OrderCheckpointRepository::get_list_by_where($arr_where,$arr_option,$arr_search)->toarray();
//        $data = list_page_data_for_api($res);
//        $data['data'] = collect($data['data'])->map(function ($item, $key){
//            $o_check_vehicle = collect($item['check_vehicle']);
//
//            $item['vehicle_waiting_num'] = intval($o_check_vehicle->whereIn('check_state',[0,1])->count());
//            $item['vehicle_complete_num'] = intval($o_check_vehicle->where('check_state',2)->count());
//            $item['vehicle_fail_num'] = intval($o_check_vehicle->where('check_state',9)->count());
//            return $item;
//        })->toArray();
//        return  hello_success('成功',$data);
//    }

//    /**
//     * 检测站-待处理预约订单-商家
//     *
//     * @param int   $n_shop_id
//     * @param array $arr_search
//     *
//     * @return array
//     * @author wumengmeng <wu_mengmeng@foxmail.com>
//     */
//    public function api_deal_order_list_for_shop($n_shop_id = 0,$arr_search = []){
//        $arr_where['shop_id'] = $n_shop_id;
//        $arr_where['pay_state'] = 2;
//        $arr_where['appointment_state'] = 2;
//        $arr_where['complete_state'] = -1;
//        $arr_option['with'] = ['check_vehicle','shop','user','user_company'];
//        $res = OrderCheckpointRepository::get_list_by_where($arr_where,$arr_option,$arr_search)->toarray();
//        $data = list_page_data_for_api($res);
//        $data['data'] = collect($data['data'])->map(function ($item, $key){
//            $o_check_vehicle = collect($item['check_vehicle']);
//
//            $item['vehicle_waiting_num'] = intval($o_check_vehicle->whereIn('check_state',[0,1])->count());
//            $item['vehicle_complete_num'] = intval($o_check_vehicle->where('check_state',2)->count());
//            $item['vehicle_fail_num'] = intval($o_check_vehicle->where('check_state',9)->count());
//            return $item;
//        })->toArray();
//        return  hello_success('成功',$data);
//    }

    /**
     * 对订单进行整单操作前，检查是否可执行整单操作
     *
     * @param $n_id
     * @param $n_shop_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function check_before_whole_operation($n_id,$n_shop_id,$arr_order){

        if($arr_order['shop_id'] != $n_shop_id){
            return hello_error('只能处理自己店的订单');
        }

        //订单预约日以及之后才能对订单进行检测完成操作
        $res = OrderCheckpointService::check_before_appoint_date_and_order_state($arr_order);
        if($res['state'] != 0){
            return $res;
        }

        //已有子单被处理 不能能统一批量处理子单
        $n_count_deal = OrderCheckpointVehicleRepository::get_count_for_deal_vehicle($n_id);
        if($n_count_deal > 0){
            return hello_error('已有子单被处理，无法全部检测完成');
        }

        //已有子单申请退款 不能能统一批量处理子单
        $n_count_apply = OrderCheckpointVehicleRepository::get_count_for_apply_vehicle($n_id);
        if($n_count_apply > 0){
            return hello_error('已有子单申请退款，无法全部检测完成');
        }

        return  hello_success('成功');
    }

    /**
     * 整单处理订单 主单+车辆子单(全部检测完成处理)
     *
     * @param $n_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function deal_complete_all($n_id){
        //处理订单 主单+车辆子单
        $s_checked_at = time_to_ymdhis();

        //主单
        $arr_data = [
          'id'=>$n_id,
          'check_state'=>2,
          'appraise_state'=>1,
          'checked_at'=>$s_checked_at
        ];
        $res = OrderCheckpointRepository::edit_one($arr_data);
        if(!$res){
            return hello_error('操作失败1');
        }

        //车辆子单
        $arr_where = ['order_checkpoint_id'=>$n_id];
        $arr_data = [
          'check_state'=>2,
          'checked_at'=>$s_checked_at
        ];
        $res = OrderCheckpointVehicleRepository::edit_by_where($arr_where, $arr_data);
        if(!$res){
            return hello_error('操作失败2');
        }
        return  hello_success('操作成功');
    }

    /**
     * 年检预约订单 - 检测完成(全部车)
     *
     * @param int $n_id order_checkpoint表id
     * @param int $n_shop_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_deal_complete_all($n_id,$n_shop_id){

        //查询订单信息
        if($n_id <= 0){
            return hello_error('数据id不能为空');
        }
        $res = OrderCheckpointRepository::api_get_detail($n_id)->toarray();
        $arr_order = $res;

        //对订单进行整单操作前，检查是否可执行整单操作
        $res = OrderCheckpointService::check_before_whole_operation($n_id,$n_shop_id,$arr_order);
        if($res['state'] != 0){
            return $res;
        }

        //处理订单 主单+车辆子单(全部检测完成处理)
        $res = OrderCheckpointService::deal_complete_all($n_id);
        return $res;
    }

    /**
     * 整单处理订单 主单+车辆子单(全部检测失败处理)
     *
     * @param $n_id
     * @param $arr_order
     * @param $s_remark
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function deal_fail_all($n_id,$arr_order,$s_remark){

        $s_refund_time = time_to_ymdhis();
        $n_check_state = 9;
        $n_apply_refund_state = 2;

        //主单
        $arr_data = [
          'id'=>$n_id,
          'check_state'=>$n_check_state,
          'refund_state'=>3,
//          'refund_price'=>$arr_order['price'],
//          'refund_time'=>$s_refund_time,
          'deal_remarks'=>$s_remark,
          'checked_at'=>$s_refund_time
        ];
        $res = OrderCheckpointRepository::edit_one($arr_data);
        if(!$res){
            return hello_error('操作失败1');
        }

        //车辆子单
        $arr_where = ['order_checkpoint_id'=>$n_id];
        $arr_data = [
//          'apply_refund_state'=>$n_apply_refund_state,
//          'refund_state'=>2,
//          'refund_time'=>$s_refund_time,
          'check_state'=>$n_check_state,
          'checked_at'=>$s_refund_time,
//          'refund_remarks'=>$s_remark
        ];
        $res = OrderCheckpointVehicleRepository::edit_by_where($arr_where, $arr_data);
        if(!$res){
            return hello_error('操作失败2');
        }

        //添加退款申请
        $arr_data = [
          'type'=>13,
          'order_sn'=>$arr_order['order_sn'],
          'order_checkpoint_vehicle_id'=>0,
          'refund_sn'=>order_sn_njtk(),
          'refund_price'=>$arr_order['price'],
          'apply_refund_state'=>$n_apply_refund_state,
//          'refund_state'=>1,
          'shop_refund_reason'=>$s_remark,
//          'remarks'=>$s_remarks,
        ];
        $res = OrderCheckpointRefundRepository::add_one($arr_data)->toarray();
        if(empty($res)){
            return hello_error('操作失败');
        }
        return hello_success('操作成功');

    }

    /**
     * 年检预约订单 - 检测失败(全部车-退款)-操作
     *
     * @param $n_id
     * @param $n_shop_id
     * @param $s_remark
     *
     * @return array|mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_deal_fail_all($n_id,$n_shop_id,$s_remark){

        //查询订单信息
        if($n_id <= 0){
            return hello_error('数据id不能为空');
        }
        if(strlen($s_remark) <= 0){
            return hello_error('请填写备注');
        }
        $res = OrderCheckpointRepository::api_get_detail($n_id)->toarray();
        $arr_order = $res;

        //对订单进行整单操作前，检查是否可执行整单操作
        $res = OrderCheckpointService::check_before_whole_operation($n_id,$n_shop_id,$arr_order);
        if($res['state'] != 0){
            return $res;
        }

        //处理订单 主单+车辆子单(全部检测失败处理)
        $res = OrderCheckpointService::deal_fail_all($n_id,$arr_order,$s_remark);
        return $res;

    }

    /**
     * 对订单进行整单操作前，检查是否可执行整单操作
     *
     * @param $n_shop_id
     * @param $arr_order
     * @param $arr_order_vehicle
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function check_before_single_operation($n_shop_id,$arr_order,$arr_order_vehicle){

        if($arr_order['shop_id'] != $n_shop_id){
            return hello_error('只能处理自己店的订单');
        }

        //主订单状态判断
        $n_pay_state = $arr_order['pay_state'];
        $n_appointment_state = $arr_order['appointment_state'];
        $n_complete_state = $arr_order['complete_state'];
        $n_real_state = $n_pay_state == 2 && $n_appointment_state == 2 && $n_complete_state == -1;
        if( !$n_real_state ){
            $s_error = '主订单状态异常:pay_state='.$n_pay_state.',appointment_state='.$n_appointment_state.',complete_state='.$n_complete_state;
            return hello_error('订单状态异常，无法操作',[],$s_error);
        }

        //车辆子单状态判断
        $nn_check_state = $arr_order_vehicle['check_state'];
        $nn_apply_refund_state = $arr_order_vehicle['apply_refund_state'];
        $n_real_state = ($nn_check_state == 1 && $nn_apply_refund_state == 0) || ($nn_check_state == 10 && $nn_apply_refund_state == 9);

        if( !$n_real_state ){
            $s_error = '车辆子订单状态异常:check_state='.$nn_check_state.',apply_refund_state='.$nn_apply_refund_state;
            return hello_error('订单状态异常，无法操作',[],$s_error);
        }
//
//        //订单预约日以及之后才能对订单进行检测失败-退款操作
//        $res = OrderCheckpointService::check_before_appoint_date_and_order_state($arr_order);
//        if($res['state'] != 0){
//            return $res;
//        }

        return  hello_success('成功');
    }

    /**
 * 单个处理订单 主单+车辆子单(单辆车-检测合格)
 *
 * @param $n_id
 * @param $n_order_id
 *
 * @return array
 * @author wumengmeng <wu_mengmeng@foxmail.com>
 */
    public function single_check_ok($n_id,$n_order_id){
        //处理订单 主单+车辆子单
        $s_checked_at = time_to_ymdhis();

        //车辆子单
        $arr_data = [
          'id'=>$n_id,
          'check_state'=>2,
          'checked_at'=>$s_checked_at
        ];
        $res = OrderCheckpointVehicleRepository::edit_one($arr_data);
        if(!$res){
            return hello_error('操作失败2');
        }

        //查询订单是否还有未处理的子单
        $n_count = OrderCheckpointVehicleRepository::get_count_for_undeal_vehicle($n_order_id);
        if($n_count <= 0){
            //主单
            $arr_data = [
              'id'=>$n_order_id,
              'complete_state'=>1,
              //              'appraise_state'=>1,
              'complete_time'=>$s_checked_at
            ];
            $res = OrderCheckpointRepository::edit_one($arr_data);
            if(!$res){
                return hello_error('操作失败1');
            }
        }

        return  hello_success('操作成功');
    }

    /**
     * 单个处理订单 主单+车辆子单(单辆车-检测不合格)
     *
     * @param $n_id
     * @param $n_order_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function single_check_not_ok($n_id,$n_order_id){
        //处理订单 主单+车辆子单
        $s_checked_at = time_to_ymdhis();

        //车辆子单
        $arr_data = [
          'id'=>$n_id,
          'check_state'=>3,
          'checked_at'=>$s_checked_at
        ];
        $res = OrderCheckpointVehicleRepository::edit_one($arr_data);
        if(!$res){
            return hello_error('操作失败2');
        }

        //查询订单是否还有未处理的子单
        $n_count = OrderCheckpointVehicleRepository::get_count_for_undeal_vehicle($n_order_id);
        if($n_count <= 0){
            //主单
            $arr_data = [
              'id'=>$n_order_id,
              'complete_state'=>1,
              //              'appraise_state'=>1,
              'complete_time'=>$s_checked_at
            ];
            $res = OrderCheckpointRepository::edit_one($arr_data);
            if(!$res){
                return hello_error('操作失败1');
            }
        }


        return  hello_success('操作成功');
    }

    /**
     * 年检预约订单 - 检测合格
     *
     * @param int $n_id order_checkpoint_vehicle
     * @param int $n_shop_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_deal_complete_single($n_id,$n_shop_id){

        //查询订单-车辆子单信息
        if($n_id <= 0){
            return hello_error('数据id不能为空');
        }
        $res = OrderCheckpointVehicleRepository::get_one($n_id, ['with'=>['order_checkpoint']])->toarray();
        $arr_order_vehicle = $res;
        $arr_order = $arr_order_vehicle['order_checkpoint'];

        //对订单进行整单操作前，检查是否可执行整单操作
        $res = OrderCheckpointService::check_before_single_operation($n_shop_id,$arr_order,$arr_order_vehicle);
        if($res['state'] != 0){
            return $res;
        }

        //单个处理订单 主单+车辆子单(单辆车-检测合格)
        $n_order_id = $arr_order['id'];
        $res = OrderCheckpointService::single_check_ok($n_id,$n_order_id);

        if($res['state'] == 0){
            /*通知队列-塞入车辆子单检测成功（合格）通知*/
            $n_order_vehicle_id = $n_id;
            queue_in_notice_order_check($n_order_id,$n_order_vehicle_id,'ok');
        }

        return $res;

    }


    /**
     * 年检预约订单 - 检测不合格
     *
     * @param int $n_id order_checkpoint_vehicle
     * @param int $n_shop_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_single_check_not_ok($n_id,$n_shop_id){

        //查询订单-车辆子单信息
        if($n_id <= 0){
            return hello_error('数据id不能为空');
        }
        $res = OrderCheckpointVehicleRepository::get_one($n_id, ['with'=>['order_checkpoint']])->toarray();
        $arr_order_vehicle = $res;
        $arr_order = $arr_order_vehicle['order_checkpoint'];

        //对订单进行整单操作前，检查是否可执行整单操作
        $res = OrderCheckpointService::check_before_single_operation($n_shop_id,$arr_order,$arr_order_vehicle);
        if($res['state'] != 0){
            return $res;
        }

        //单个处理订单 主单+车辆子单(单辆车-检测不合格)
        $n_order_id = $arr_order['id'];
        $res = OrderCheckpointService::single_check_not_ok($n_id,$n_order_id);

        if($res['state'] == 0){

            /*通知队列-塞入车辆子单检测成功（不合格）通知*/
            $n_order_vehicle_id = $n_id;
            queue_in_notice_order_check($n_order_id,$n_order_vehicle_id,'not_ok');
        }
        return $res;

    }

    /**
     * 单个处理订单 主单+车辆子单(单个检测失败处理)
     *
     * @param $n_id
     * @param $arr_order
     * @param $arr_order_vehicle
     * @param $s_remark
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function deal_fail_single($n_id,$arr_order,$arr_order_vehicle,$s_remark,$s_fail_type){
        $refund_fee = $arr_order_vehicle['price'];
        $s_refund_time = time_to_ymdhis();
        $n_apply_refund_state = 2;

        //处理订单 主单+车辆子单

        //车辆子单
        $arr_data = [
          'id'=>$n_id,
          'apply_refund_state'=>$n_apply_refund_state,
//          'refund_price'=>$refund_fee,
          'fail_type'=>$s_fail_type,
//          'refund_remarks'=>$s_remark,
//          'refund_time'=>$s_refund_time,
//          'refund_state'=>2,
          'check_state'=>9,
          'checked_at'=>$s_refund_time
        ];
        $res = OrderCheckpointVehicleRepository::edit_one($arr_data);
        if(!$res){
            return hello_error('操作失败2');
        }

        //添加退款申请
        $arr_data = [
          'type'=>2,
          'order_sn'=>$arr_order['order_sn'],
          'order_checkpoint_vehicle_id'=>$n_id,
          'refund_sn'=>order_sn_njtk(),
          'refund_price'=>$refund_fee,
          'apply_refund_state'=>$n_apply_refund_state,
          //          'refund_state'=>1,
          'shop_refund_reason'=>$s_remark,
          //          'remarks'=>$s_remarks,
        ];
        $res = OrderCheckpointRefundRepository::add_one($arr_data)->toarray();
        if(empty($res)){
            return hello_error('操作失败');
        }

        //查询订单是否还有未处理的子单  TODO 这一步不进行处理，等到退款时在进行修改主单状态的操作
//        $res = OrderCheckpointService::deal_fail_single_other($arr_order['id'],$s_refund_time);
//        return $res;

        return  hello_success('成功');

    }

    /**
     * 单个失败主表状态联动
     *
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     *
     * @param $n_order_id
     * @param $s_refund_time
     *
     * @return array
     */
    public function deal_fail_single_other($n_order_id,$s_refund_time){

        //查询订单是否还有未处理的子单
        $n_count = OrderCheckpointVehicleRepository::get_count_for_undeal_vehicle($n_order_id);
        if($n_count <= 0){

            //查询检测成功的子单数量
            $arr_wherein = [2,3];
            $n_success_count = OrderCheckpointVehicleRepository::get_count_for_check_success($n_order_id,$arr_wherein);
            if($n_success_count <= 0){
                //全部失败
                $arr_data = [
                  'id'=>$n_order_id,
                  'appointment_state'=>3,
                  'complete_state'=>3,
                  'refund_state'=>4,
                  'complete_time'=>$s_refund_time
                ];

            }else{
                //检测完成 部分失败
                $arr_data = [
                  'id'=>$n_order_id,
                  'complete_state'=>1,
//                  'appraise_state'=>1,
                  'complete_time'=>$s_refund_time
                ];
            }

        }
        else{
            $arr_data = [
              'id'=>$n_order_id,
              'refund_state'=>2,
//              'checked_at'=>$s_refund_time
            ];
        }

        //主单
        $res = OrderCheckpointRepository::edit_one($arr_data);
        if($res === false){
            return hello_error('操作失败');
        }

        return hello_success('操作成功');
    }

    /**
     * 年检预约订单 故障- 检测失败(单辆车-退款)-操作
     *
     * @param        $n_id
     * @param        $n_shop_id
     * @param        $s_remark
     * @param string $s_fail_type
     *
     * @return array|mixed
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_deal_fail_single($n_id,$n_shop_id,$s_remark,$s_fail_type = ''){

        //查询订单-车辆子单信息
        if($n_id <= 0){
            return hello_error('数据id不能为空');
        }
        $res = OrderCheckpointVehicleRepository::get_one($n_id, ['with'=>['order_checkpoint']])->toarray();
        $arr_order_vehicle = $res;
        $arr_order = $arr_order_vehicle['order_checkpoint'];

        //对订单进行整单操作前，检查是否可执行整单操作
        $res = OrderCheckpointService::check_before_single_operation($n_shop_id,$arr_order,$arr_order_vehicle);
        if($res['state'] != 0){
            return $res;
        }
//        if($arr_order_vehicle['apply_refund_state'] == 9){
//            return hello_error('该车辆已拒绝退款，无法进行再去检测完成');
//        }

        //单个处理订单 主单+车辆子单(故障)
        $res = OrderCheckpointService::deal_fail_single($n_id,$arr_order,$arr_order_vehicle,$s_remark,$s_fail_type);

        if($res['state'] == 0){

            /*通知队列-塞入车辆子单检测成功（不合格）通知*/
            $n_order_id = $arr_order['id'];
            $n_order_vehicle_id = $n_id;
            queue_in_notice_order_check($n_order_id,$n_order_vehicle_id,'fail');
        }

        return $res;


    }

    /**
     * 操作订单前检测预约日期和订单状态
     *
     * @param $arr_order
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function check_before_appoint_date_and_order_state($arr_order){
        $s_appoint_date = $arr_order['appointment_date'];

        //订单前置态检查
        $n_pay_state = $arr_order['pay_state'];
//        $n_refund_state = $arr_order['refund_state'];
        $n_appointment_state = $arr_order['appointment_state'];
//        $n_check_state = $arr_order['check_state'];
//        $n_appraise_state = $arr_order['appraise_state'];
        $n_state =
          ($n_pay_state == 2)
//          && (in_array($n_refund_state,[0,1]))
          && ($n_appointment_state == 2)
//          && ($n_check_state == 1)
//          && ($n_appraise_state == 0)
        ;
        if(!$n_state){
            return hello_error('订单状态错误，请联系管理员');
        }

        return  hello_success('成功');
    }

//    public function api_apply_refund($n_uid = 0,$arr_input = []){
//
//        ///// 1-数据准备
//        $n_id = intval($arr_input['id']);//年检预约单id
//        $s_refund_reason = str_trim($arr_input['refund_reason']);//退款原因
//        $s_remarks = str_trim($arr_input['remarks']);//备注
//        $s_now_date = date('Y-m-d');
//        if($n_uid <= 0){
//            return hello_error('用户id不能为空');
//        }
//        if($n_id <= 0){
//            return hello_error('年检预约单id不能为空');
//        }
//
//        ///// 2-核对逻辑
//        //查询预约日期 只有预约日期以及之前才可以申请退款
//        $arr_option = [
//          'field'=>['id','appointment_date','order_sn','pay_state','refund_state','appointment_state','check_state','appraise_state','user_id'],
//        ];
//        $res = OrderCheckpointRepository::base_find_one($n_id,$arr_option);
//        if(is_null($res)){
//            return hello_error('没有订单数据');
//        }
//        $arr_order_checkpoint = $res->toarray();
//        if($n_uid != $arr_order_checkpoint['user_id']){
//            return hello_error('用户只能操作自己的订单');
//        }
//        if($s_now_date > $arr_order_checkpoint['appointment_date']){
//            return hello_error('只有预约日期以及之前才可以申请退款');
//        }
//
//        //查询所有车辆子单信息
//        $arr_option = [
//          'field'=>['id','check_state','apply_refund_state','price'],
//          'where'=>['order_checkpoint_id'=>$n_id],
//        ];
//        $arr_order_vehicle = OrderCheckpointVehicleRepository::base_get_all($arr_option)->toarray();
//        $n_apply_refund_state = collect($arr_order_vehicle)->where('apply_refund_state','>',0)->count();
//        $n_check_state = collect($arr_order_vehicle)->where('check_state','!=',1)->count();
//        $n_count_order_vehicle = count($arr_order_vehicle);
//        if( $n_apply_refund_state != 0 ){
//            if($n_apply_refund_state != $n_count_order_vehicle){
//                return hello_error('已有车辆子单申请，无法申请整单退款');
//            }
//            else{
//                return hello_error('已申请退款，请勿重复申请');
//            }
//        }
//        if($n_check_state != 0){
//            return hello_error('车辆已检测，无法申请退款');
//        }
//
//
//        ///// 3-提交申请
//
//        //车辆子单状态修改
//        $arr_where = ['order_checkpoint_id'=>$n_id];
//        $arr_data = ['apply_refund_state'=>1];
//        $res = OrderCheckpointVehicleRepository::edit_by_where($arr_where,$arr_data);
//        if($res === false){
//            return hello_error('申请失败',[],'修改车辆子单状态失败');
//        }
//
//        //申请退款
//        $arr_data = [];
//        foreach ($arr_order_vehicle as $value)
//        {
//            $arr_data[] = [
//              'type'=>1,
//              'order_sn'=>$arr_order_checkpoint['order_sn'],
//              'order_checkpoint_vehicle_id'=>$n_id,
//              'refund_sn'=>order_sn_njtk(),
//              'refund_price'=>$value['price'],
//              'apply_refund_state'=>1,
//              //          'refund_state'=>1,
//              'refund_reason'=>$s_refund_reason,
//              'remarks'=>$s_remarks,
//            ];
//        }
//        $res = OrderCheckpointRefundRepository::base_add_many($arr_data);
//        if(!$res){
//            return hello_error('申请失败',[],'申请退款失败');
//        }
//        return hello_success('申请成功');
//    }

//    /**
//     * 车辆子单申请退款
//     *
//     * @param int   $n_uid
//     * @param array $arr_input
//     *
//     * @return array
//     * @author wumengmeng <wu_mengmeng@foxmail.com>
//     */
//    public function api_apply_refund_for_vehicle($n_uid = 0,$arr_input = []){
//
//        ///// 1-数据准备
//        $n_id = intval($arr_input['id']);//年检预约单-车辆子表id
//        $s_refund_reason = str_trim($arr_input['refund_reason']);//退款原因
//        $s_remarks = str_trim($arr_input['remarks']);//备注
//        $s_now_date = date('Y-m-d');
//        if($n_uid <= 0){
//            return hello_error('用户id不能为空');
//        }
//        if($n_id <= 0){
//            return hello_error('车辆子单id不能为空');
//        }
//
//        ///// 2-核对逻辑
//        //查询预约日期 只有预约日期以及之前才可以申请退款
//        $arr_field = ['id','appointment_date','order_sn','pay_state','refund_state','appointment_state','check_state','appraise_state'];
//        $res = OrderCheckpointRepository::get_one_by_vehicle_id($n_id,$arr_field);
//        if(is_null($res)){
//            return hello_error('没有订单数据',[],'没有年检预约单数据');
//        }
//        $arr_order_checkpoint = $res->toarray();
//        if($s_now_date > $arr_order_checkpoint['appointment_date']){
//            return hello_error('只有预约日期以及之前才可以申请退款');
//        }
//
//        //查询车辆子单信息
//        $arr_order_vehicle = OrderCheckpointVehicleRepository::find_one($n_id,['id','check_state','apply_refund_state','price'])->toarray();
//        if(empty($arr_order_vehicle)){
//            return hello_error('没有订单数据',[],'没有年检预约单-车辆子单数据');
//        }
//        if($arr_order_vehicle['check_state'] != 1){
//            return hello_error('车辆已检测，无法申请退款');
//        }
//        if($arr_order_vehicle['apply_refund_state'] != 0){
//            return hello_error('已申请退款，请勿重复申请');
//        }
//
//        ///// 3-提交申请
//
//        //车辆子单状态修改
//        $arr_where = ['id'=>$n_id];
//        $arr_data = ['apply_refund_state'=>1];
//        $res = OrderCheckpointVehicleRepository::edit_by_where($arr_where,$arr_data);
//        if($res === false){
//            return hello_error('申请失败',[],'车辆子单修改状态失败');
//        }
//        $arr_data = [
//          'type'=>1,
//          'order_sn'=>$arr_order_checkpoint['order_sn'],
//          'order_checkpoint_vehicle_id'=>$n_id,
//          'refund_sn'=>order_sn_njtk(),
//          'refund_price'=>$arr_order_vehicle['price'],
//          'apply_refund_state'=>1,
//          //          'refund_state'=>1,
//          'refund_reason'=>$s_refund_reason,
//          'remarks'=>$s_remarks,
//        ];
//        $res = OrderCheckpointRefundRepository::add_one($arr_data)->toarray();
//        if(empty($res)){
//            return hello_error('申请失败');
//        }
//        return hello_success('申请成功');
//    }

    /**
     * 多选车辆子单申请退款
     *
     * @param int   $n_uid
     * @param array $arr_input
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_apply_refund_for_more_vehicle($n_uid = 0,$arr_input = []){

        ///// 1-数据准备
        $n_id = intval($arr_input['order_checkpoint_id']);//年检预约单id
        $arr_vehicle_ids = $arr_input['order_checkpoint_vehicle_ids'];//
        $arr_real_vehicle_ids = array_flip(array_flip($arr_vehicle_ids));//
        $s_refund_reason = str_trim($arr_input['refund_reason']);//退款原因
        $s_remarks = str_trim($arr_input['remarks']);//备注
        $s_now_date = date('Y-m-d');
        if($n_uid <= 0){
            return hello_error('用户id不能为空');
        }
        if($n_id <= 0){
            return hello_error('年检预约单id不能为空');
        }
        if(count($arr_vehicle_ids) != count($arr_real_vehicle_ids)){
            return hello_error('不要重复勾选同一个车辆');
        }

        ///// 2-核对逻辑
        $result = OrderCheckpointRepository::get_one_for_apply_refund($n_id);
        if(is_null($result)){
            return hello_error('没有订单数据',[],'没有年检预约单数据');
        }
        $result = $result->toarray();
        $arr_order_vehicle = $result['apply_vehicle'];
        unset($result['apply_vehicle']);
        $arr_order = $result;

        /// 主单逻辑核对
        $n_pay_state = $arr_order['pay_state'];
        $n_appointment_state = $arr_order['appointment_state'];
        $n_complete_state = $arr_order['complete_state'];
        $n_real_state = $n_pay_state == 2 && $n_appointment_state == 2 && $n_complete_state == -1;
        if( !$n_real_state ){
            return hello_error('订单状态异常，不能申请退款');
        }

        /// 子单必须属于同一个主单
        if(count($arr_real_vehicle_ids) <= 0){
            return hello_error('请选择退款子单');
        }
        $arr_real_vehicle = collect($arr_order_vehicle)->whereIn('id',$arr_real_vehicle_ids)->toArray();
        if(count($arr_real_vehicle) != count($arr_real_vehicle_ids)){
            return hello_error('请选择同一订单下的车辆子单');
        }

        /// 子单逻辑核对 check_state = 1 apply_refund_state = 0
        $n_apply_state = 1;
        $arr_refund_data = [];
        foreach ($arr_real_vehicle as $value)
        {
            $n_check_state = intval($value['check_state']);
            $n_apply_refund_state = intval($value['apply_refund_state']);
            if(!($n_check_state == 1 && $n_apply_refund_state == 0)){
                //检测状态
                if($n_check_state == 2){
                    return hello_error('车辆已检测-合格，无法申请退款');
                }
                elseif($n_check_state == 3){
                    return hello_error('车辆已检测-不合格，无法申请退款');
                }
                elseif($n_check_state == 9){
                    return hello_error('车辆不符合检测条件，无法申请退款');
                }
                elseif($n_check_state == 10){
                    return hello_error('车辆用户已申请退款，无法申请退款');
                }

                //申请状态
                if($n_apply_refund_state == 1){
                    return hello_error('申请中，无法申请退款');
                }
                elseif($n_apply_refund_state == 2){
                    return hello_error('待退款，无法申请退款');
                }
                elseif($n_apply_refund_state == 3){
                    return hello_error('已退款，无法申请退款');
                }
                elseif($n_apply_refund_state == 10){
                    return hello_error('申请被拒，无法申请退款');
                }
            }

            $arr_refund_data[] = [
              'type'=>1,
              'order_sn'=>$arr_order['order_sn'],
              'order_checkpoint_vehicle_id'=>$value['id'],
              'refund_sn'=>order_sn_njtk(),
              'refund_price'=>$value['price'],
              'apply_refund_state'=>$n_apply_state,
              'refund_reason'=>$s_refund_reason,
              'remarks'=>$s_remarks,
            ];
        }
 

        ///// 3-提交申请

        //车辆子单状态修改
        $arr_data = [ 'check_state'=>10,'apply_refund_state'=>$n_apply_state];
        $res = OrderCheckpointVehicleRepository::base_edit_by_wherein($arr_real_vehicle_ids,$arr_data);
        if($res === false){
            return hello_error('申请失败',[],'车辆子单修改状态失败');
        }

        $res = OrderCheckpointRefundRepository::base_add_many($arr_refund_data);
        if($res === false){
            return hello_error('申请失败');
        }
        return hello_success('申请成功');
    }
    /**
     * 车辆子单申请退款
     *
     * @param int    $n_uid
     * @param int    $n_id
     * @param string $s_refund_reason
     * @param string $s_remarks
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_apply_refund_for_appointment_vehicle($n_uid = 0,$n_id = 0,$s_refund_reason = '',$s_remarks = ''){
        $n_uid = intval($n_uid);
        $n_id = intval($n_id);
        $s_now_date = date('Y-m-d');
        if($n_uid <= 0){
            return hello_error('用户id不能为空');
        }
        if($n_id <= 0){
            return hello_error('车辆子单id不能为空');
        }

        //查询预约日期 只有预约日期以及之前才可以申请退款
        $arr_field = ['id','appointment_date','order_sn','pay_state','refund_state','appointment_state','check_state','appraise_state'];
        $res = OrderCheckpointRepository::get_one_by_vehicle_id($n_id,$arr_field);
        if(is_null($res)){
            return hello_error('没有订单数据');
        }
        $arr_order_checkpoint = $res->toarray();
        if($s_now_date > $arr_order_checkpoint['appointment_date']){
            return hello_error('只有预约日期以及之前才可以申请退款');
        }
//        if($arr_order_checkpoint['check_state'] != 1){
//            return hello_error('订单不能符合申请退款条件');
//        }

        //查询车辆子单信息
        $arr_order_vehicle = OrderCheckpointVehicleRepository::find_one($n_id,['id','check_state','apply_refund_state','price'])->toarray();
        if(empty($arr_order_vehicle)){
            return hello_error('没有订单数据1');
        }
        if($arr_order_vehicle['check_state'] != 1){
            return hello_error('车辆已检测，无法申请退款');
        }
        if($arr_order_vehicle['apply_refund_state'] != 0){
            return hello_error('已申请退款，请勿重复申请');
        }

        //车辆子单状态修改
        $arr_where = ['id'=>$n_id];
        $arr_data = ['apply_refund_state'=>1];
        $res = OrderCheckpointVehicleRepository::edit_by_where($arr_where,$arr_data);
        if($res === false){
            return hello_error('申请失败-1');
        }
        //申请退款：1每个车辆子单只能申请一次退款 2申请退款前先查询是否已有申请
//        $arr_where = ['order_checkpoint_vehicle_id'=>$n_id];
//        $n_count = OrderCheckpointRefundRepository::get_count_by_where($arr_where);
//        if($n_count > 0){
//            return hello_error('已申请退款，请勿重复申请');
//        }

        $arr_data = [
          'type'=>1,
          'order_sn'=>$arr_order_checkpoint['order_sn'],
          'order_checkpoint_vehicle_id'=>$n_id,
          'refund_sn'=>order_sn_njtk(),
          'refund_price'=>$arr_order_vehicle['price'],
          'apply_refund_state'=>1,
//          'refund_state'=>1,
          'refund_reason'=>$s_refund_reason,
          'remarks'=>$s_remarks,
        ];
        $res = OrderCheckpointRefundRepository::add_one($arr_data)->toarray();
        if(empty($res)){
            return hello_error('申请失败');
        }
        return hello_success('申请成功');

    }


    public function api_simulate_pay($n_id){
        $arr_field = ['id', 'shop_id', 'user_id','appointment_date', 'appointment_times', 'appointment_time_type', 'appointment_num', 'pay_state','appointment_state', 'created_at'];
        $result = OrderCheckpointRepository::base_find_one($n_id,['field'=>$arr_field]);
        if(is_null($result)){
            return hello_error('订单不存在');
        }
        $result = $result->toarray();

        //只有未支付的订单才可以支付
        if(!($result['pay_state'] == 1 && $result['appointment_state'] == 1) ){
            if ($result['pay_state'] == 2 && $result['appointment_state'] == 2 ){
                return hello_error('订单已支付成功，请勿重复');
            }
            return hello_error('订单状态错误，无法支付');
        }

        //确认支付 + 预约成功 + 支付时间
        $n_time = time_to_ymdhis();
        $arr_where = ['id'=>$n_id];
        $arr_data = [
            //          'payment_method'=>'wechat_pay',
            'appointment_state'=>2,
            'pay_state'=>2,
            'complete_state'=>-1,
            //            'refund_state'=>0,
            //            'check_state'=>1,
            //            'appraise_state'=>0,
            'pay_time'=>$n_time,
        ];
        $res = OrderCheckpointRepository::edit_by_where($arr_where,$arr_data);
        if($res === false){
            return hello_error('确认失败-1');
        }

        //子表状态处理
        $arr_where = ['order_checkpoint_id'=>$n_id];
        $arr_data = [
          'check_state'=>1,
        ];
        $res = OrderCheckpointVehicleRepository::edit_by_where($arr_where,$arr_data);
        if($res === false){
            return hello_error('确认失败-1');
        }
        return  hello_success('成功');
    }

    /**
     * 确认完成订单
     *
     * @param int $n_uid
     * @param int $n_id
     *
     * @return array
     * @author wumengmeng <wu_mengmeng@foxmail.com>
     */
    public function api_order_confirm_complete($n_uid = 0,$n_id = 0){
        if($n_uid <= 0){
            return hello_error('用户id不能为空');
        }
        if($n_id <= 0){
            return hello_error('年检预约单id不能为空');
        }
        //查询订单信息
        $result = OrderCheckpointRepository::base_find_one($n_id);
        if(is_null($result)){
            return hello_error('没有订单数据',[],'没有年检预约单数据');
        }
        $result = $result->toarray();

        //条件判断
        if($result['complete_state'] != 1){
            $s_msg = 'error:'.$result['complete_state'];
            return hello_error('订单状态异常，不能确认完成',[],$s_msg);
        }
        if($result['user_id'] != $n_uid){
            return hello_error('用户只能操作自己的订单');
        }

        //确认订单
        $arr_data = [
          'id'=>$n_id,
          'complete_state'=>2,
          'appraise_state'=>1,
          'is_finish'=>1,
          'complete_time'=>time_to_ymdhis(),
        ];
        $res = OrderCheckpointRepository::base_edit_one($arr_data);
        if($res === false){
            return hello_error('确认失败');
        }
        return  hello_success('确认成功');

    }


}